package org.dfzt.modules.system.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dfzt.common.constant.CommonConstant;
import org.dfzt.common.system.service.ISysBaseAPI;
import org.dfzt.common.system.util.JwtUtil;
import org.dfzt.common.util.SpringContextUtils;
import org.dfzt.modules.message.service.SendMessageService;
import org.dfzt.modules.message.service.impl.SendMessageServiceImpl;
import org.dfzt.modules.system.entity.SysLog;
import org.dfzt.modules.system.entity.SysUser;
import org.dfzt.modules.system.entity.SysUserRole;
import org.dfzt.modules.system.service.ISysLogService;
import org.dfzt.modules.system.service.ISysUserRoleService;
import org.dfzt.modules.system.service.ISysUserService;
import org.dfzt.modules.system.service.impl.SysBaseApiImpl;
import org.dfzt.modules.system.service.impl.SysLogServiceImpl;
import org.dfzt.modules.system.service.impl.SysUserRoleServiceImpl;
import org.dfzt.modules.system.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class UserJob implements SimpleJob {
    private final static Log log = LogFactory.getLog(UserJob.class);
    private static final Integer MAX_DAY_TIME = 8;//提前8天开始记录异常告警，推送给管理员

    private static final String adminRoleId = "f6817f48af4fb3af11b9e8bf182f618b";
//    @Value(value = "${adminRoleId}")
//    private String adminRoleId;

    private ISysUserService sysUserService;
    private ISysLogService sysLogService;
    private ISysBaseAPI sysBaseAPI;
    private SendMessageService sendMessageService;
    private ISysUserRoleService sysUserRoleService;

    /**
     * 一天执行一次
     * */
    @Override
    public void execute(ShardingContext shardingContext) {
        log.info("---------------------------UserJob定时任务，开始处理用户-----------------------");
        if (sysUserService == null) {
            sysUserService = SpringContextUtils.getBean(SysUserServiceImpl.class);
        }
        if (sysLogService == null) {
            sysLogService = SpringContextUtils.getBean(SysLogServiceImpl.class);
        }
        if (sysBaseAPI == null) {
            sysBaseAPI = SpringContextUtils.getBean(SysBaseApiImpl.class);
        }
        if (sendMessageService == null){
            sendMessageService = SpringContextUtils.getBean(SendMessageServiceImpl.class);
        }
        if (sysUserRoleService == null){
            sysUserRoleService = SpringContextUtils.getBean(SysUserRoleServiceImpl.class);
        }
        Date nowTime=new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(nowTime);

        Calendar temp = Calendar.getInstance();
        //如果超过3个月未登录就置为休眠
        //查询所有正常的用户
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1);
        wrapper.eq("user_type", "2");
        List<SysUser> sysUserList = sysUserService.list(wrapper);
        List<SysUserRole> userRoleList = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, adminRoleId));
        if (sysUserList != null) {
            for (SysUser sysUser : sysUserList) {
                SysLog lastLogin = sysLogService.getLastLogin(sysUser.getUsername());
                Date lastLoginTime = null;
                if (lastLogin != null) {
                    lastLoginTime = lastLogin.getCreateTime();
                } else {//表示从未登陆
                    lastLoginTime = sysUser.getCreateTime();
                }
                temp.setTime(lastLoginTime);
                temp.add(Calendar.MONTH, JwtUtil.SET_SLEEP_TIME);
                //如果三个月未登陆设置为休眠状态  3
                if (temp.before(now)) {
                    sysUser.setStatus(3);
                    sysUser.setUpdateTime(nowTime);
                    sysUserService.saveOrUpdate(sysUser);
                    log.info("----用户" + sysUser.getUsername() + "长时间未登录进入休眠----");
                    sysBaseAPI.addLog("用户" + sysUser.getUsername() + "长时间未登录进入休眠", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_SUCCESS, "platform");
                    String users = getUserIds(userRoleList);
                    if (StringUtils.isNotEmpty(users)){
                        sendMessageService.sendSysAnnouncement("admin", users, "系统通知","用户" + sysUser.getUsername() + "长时间未登录已进入休眠");
                    }
                }
            }
        }

        //判断所有休眠用户是否需要注销
        //获取所有的休眠用户
        QueryWrapper<SysUser> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("status", 3);
        List<SysUser> sleepUsers = sysUserService.list(wrapper2);
        //循环判断用户的更新时间+6个月之后和当前时间作比较
        Date tempDate;
        if (sleepUsers != null) {
            for (SysUser sysUser : sleepUsers) {
                tempDate = sysUser.getUpdateTime();
                temp.setTime(tempDate);
                temp.add(Calendar.MONTH, JwtUtil.MAX_SLEEP_TIME);
                //更新时间+6个月之后，如果小于当前时间，就将状态置为注销 4，否则再进行其他判断
                if (temp.before(now)) {
//                    sysUser.setDelFlag(1);
                    sysUser.setUpdateTime(nowTime);
                    sysUserService.saveOrUpdate(sysUser);
                    sysUserService.removeById(sysUser.getId());
                    log.info("用户" + sysUser.getUsername() + "长时间未激活被注销");
                    sysBaseAPI.addLog("用户" + sysUser.getUsername() + "长时间未激活被注销", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_SUCCESS, "platform");
                    String users = getUserIds(userRoleList);
                    if (StringUtils.isNotEmpty(users)){
                        sendMessageService.sendSysAnnouncement("admin", users, "系统通知","用户" + sysUser.getUsername() + "长时间未激活被注销");
                    }
                } else {
                    //再让更新时间-8天，如果小于当前时间，就记录异常告警
                    temp.add(Calendar.DAY_OF_YEAR, -MAX_DAY_TIME);
                    if (temp.before(now)) {
                        log.info("用户" + sysUser.getUsername() + "即将注销");
                    }
                }
            }
        }
    }

    private String getUserIds(List<SysUserRole> userRoleList){
        StringBuilder builder = new StringBuilder();
        if (userRoleList!=null && !userRoleList.isEmpty()){
            userRoleList.forEach(i -> {
                SysUser user = sysUserService.getById(i.getUserId());
                if (user!=null){
                    builder.append(user.getUsername());
                    builder.append(",");
                }
            });
            builder.deleteCharAt(builder.lastIndexOf(","));
        }
        return builder.toString();
    }
}